package com.ruoyi.app.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.business.domain.JtAppUser;
import com.ruoyi.business.service.IJtAppUserService;
import com.ruoyi.business.service.IJtUserPromotionCodeRelService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.jwt.filter.JwtFilter;
import com.ruoyi.framework.jwt.utils.JwtUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author Alan Zhang
 * @Date 2025/3/31 22:26
 */
public class BaseApiController {

    @Autowired
    protected IJtAppUserService jtAppUserService;
    /**
     * 获取request
     */
    public HttpServletRequest getRequest()
    {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse()
    {
        return ServletUtils.getResponse();
    }


    public String getToken() {
        String token = WebUtils.toHttp(getRequest()).getHeader(JwtFilter.AUTHZ_HEADER);
        return token;
    }

    /**
     * Token 用户
     * @return
     */
    public JtAppUser getTokenAppUser(){
        String username = JwtUtils.getUserName(getToken());
        return jtAppUserService.checkPhoneUnique(username);
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    protected String i18n(String keyCode){
        String lang = getRequest().getParameter("lang");
        if(StringUtils.isEmpty(lang)){
            String headerLang = getRequest().getHeader("Accept-Language");
            System.out.println(headerLang);
            if(StringUtils.isNotEmpty(headerLang)){
                lang = headerLang;
            } else {
                lang = "zh_CN";
            }
        }

        return MessageUtils.message(keyCode);
    }
}
